<link th:href="@{admin/plugins/wangeditor5/style.min.css}" rel="stylesheet">
<style>
    #editor—wrapper {
        border: 1px solid #ccc;
        z-index: 100; /* 按需定义 */
    }

    #toolbar-container {
        border-bottom: 1px solid #ccc;
    }

    #editor-container {
        height: 400px;
    }
</style>

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0 text-dark">发布/编辑文章模版</h1>
            </div><!-- /.col -->
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a th:href="@{admin}" id="indexUrl">首页</a></li>
                    <li class="breadcrumb-item active">模版管理</li>
                    <li class="breadcrumb-item active">发布/编辑文章模板</li>
                </ol>
            </div><!-- /.col -->
        </div><!-- /.row -->
    </div><!-- /.container-fluid -->
</div>
<!-- Main content -->
<section class="content">
    <div class="card card-info p-3">
        <form id="articleForm" class="row">
            <input th:value="${articleTemplate?.id}" type="hidden" name="id">
            <input id="articleTemplateContent" type="hidden" name="content" th:value="${articleTemplate?.content}">
            <div class="col-lg-8">
                <div class="form-group">
                    <input type="text" class="form-control" id="title" name="title" th:value="${articleTemplate?.title}"
                           placeholder="请输入模板标题">
                </div>
                <div class="form-group">
                    <div id="editor—wrapper">
                        <div id="toolbar-container"><!-- 工具栏 --></div>
                        <div id="editor-container"><!-- 编辑器 --></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 p-3" style="border: 1px solid #ddd;border-radius: 4px;">
                <div class="form-group col-xs-12">
                    <label class="control-label">模板类型:</label>
                    <select id="category-select" class="form-control" name="tempType" required>
                        <option value="0" th:selected="${articleTemplate?.tempType == 0}">页头</option>
                        <option value="1" th:selected="${articleTemplate?.tempType == 1}">页尾</option>
                    </select>
                </div>

                <div class="form-group mt-4">
                    <div class="row">
                        <button type="button" class="btn btn-primary btn-lg col-md-4 offset-1"
                                onclick="save();">保存
                        </button>
                        <button type="button" class="btn btn-secondary btn-lg col-md-4 offset-2"
                                onclick="cancel();">取消
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>

<script th:src="@{admin/plugins/wangeditor5/index.min.js}"></script>
<script>
    var E = window.wangEditor

    var editArticle = "[[${articleTemplate.id!=null}]]";

    var MyMenu = class {
        constructor() {
            this.title = '附件'
            this.tag = 'button'
            this.showModal = true
            this.modalWidth = 300
        }

        getValue(editor) {
            return ''
        }

        isActive(editor) {
            return false // or true
        }

        isDisabled(editor) {
            return false // or true
        }

        exec(editor, value) {
            // do nothing 什么都不用做
        }

        getModalPositionNode(editor) {
            return null // modal 依据选区定位
        }

        getModalContentElem(editor) {
            const $container = $('<div></div>')

            const inputId = `input-${Math.random().toString(16).slice(-8)}`
            const buttonId = `button-${Math.random().toString(16).slice(-8)}`

            const $inputContainer = $(`<label class="babel-container">
            <span>附件</span>
            <input type="file" id="${inputId}" value="上传">
          </label>`)
            const $buttonContainer = $(`<div class="button-container">
            <button id="${buttonId}">确定</button>
          </div>`)

            $container.append($inputContainer).append($buttonContainer)

            $container.on('click', `#${buttonId}`, e => {
                e.preventDefault()

                const text = $(`#${inputId}`).val()
                if (!text) return

                let files = $(`#${inputId}`)[0].files;
                var fd = new FormData()
                fd.append('file', files[0])
                $.ajax({
                    method: 'POST',
                    url: '[[@{/attachment/upload}]]',
                    data: fd,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        console.log(res);
                        editor.restoreSelection() // 恢复选区
                        editor.dangerouslyInsertHtml('<a href="' + res.url + '">' + res.originalFileName + '</a>');
                        editor.insertText(' ')
                    }
                })
            })

            setTimeout(() => {
                $(`#${inputId}`).focus()
            })

            return $container[0]
        }
    }

    var myMenuConf = {
        key: 'myMenu',
        factory() {
            return new MyMenu()
        }
    }
    E.Boot.registerMenu(myMenuConf)

    window.editor = E.createEditor({
        selector: '#editor-container',
        content: [
            {
                type: 'paragraph',
                children: [
                    {text: '', fontFamily: '仿宋', fontSize: '16px'}
                ]
            },
        ],
        config: {
            placeholder: '请输入模板内容...',
            MENU_CONF: {
                uploadImage: {
                    //上传文件参数名，与后台接收的参数名一致
                    fieldName: 'file',
                    // 10kb 以下插入 base64
                    base64LimitSize: 10 * 1024,
                    server: '/attachment/uploadImageForEditor',
                    onFailed: function (file, res) {
                        alert(res.message);
                    }
                },
                uploadVideo: {
                    fieldName: 'file',
                    server: '/attachment/uploadForEditor',
                    // 单个文件的最大体积限制，默认为 10M
                    maxFileSize: 200 * 1024 * 1024, // 200M
                }
            },
            onChange(editor) {
                // console.log(editor.getHtml())
            }
        }
    })

    window.toolbar = E.createToolbar({
        editor,
        selector: '#toolbar-container',
        config: {
            insertKeys: {
                index: 21, // 插入的位置，基于当前的 toolbarKeys
                keys: ['myMenu']
            }
        }
    })

    // 不显示全屏按钮
    // toolbar.config.excludeKeys = [
    //     'fullScreen'
    // ]

    // esc退出editor编辑器的全屏
    document.addEventListener('keyup', function(e) {
        if (e.keyCode == 27) {
            editor.unFullScreen()
        }
    });
</script>
<script>

    function save() {
        if (validArticle()) {
            Core.confirm("确认保存模板？", function () {
                if (editArticle != 'true') {
                    Core.postAjax("/articleTemplate/add", $("#articleForm").serialize(), function (data) {
                        if (data.status === 200) {
                            editor.clear();
                            Core.load("#content", "articleTemplate/add");
                        }
                        layer.msg(data.msg)
                    })
                } else {
                    Core.postAjax("/articleTemplate/edit", $("#articleForm").serialize(), function (data) {
                        layer.msg(data.msg)
                    })
                }
            })
        }
    }

    function cancel() {
        window.location.href = $("#indexUrl").attr("href") + "#articleTemplates";
    }

    function validArticle() {
        var content = editor.getHtml();
        if (content == null || content == '' || content == '<p><br></p>') {
            layer.msg("请输入模板内容！")
            return false;
        } else {
            $("#articleTemplateContent").val(content);
        }
        if ($("#title").val() == null || $("#title").val() == '') {
            layer.msg("请输入模板标题！")
            return false;
        }
        return true;
    }

    $(function () {
        if (editArticle == 'true') {
            window.editor.setHtml($('#articleTemplateContent').val());
        }
    });
</script>
